package it.upnp.device;
import org.apache.log4j.Logger;
import org.cybergarage.upnp.Action;
import org.cybergarage.upnp.Argument;
import org.cybergarage.upnp.ArgumentList;
import org.cybergarage.upnp.Device;
import org.cybergarage.upnp.StateVariable;
import org.cybergarage.upnp.control.ActionListener;
import org.cybergarage.upnp.control.QueryListener;
import org.cybergarage.upnp.device.InvalidDescriptionException;


public class LightDevice extends Device implements ActionListener, QueryListener {
	
	private static final String descriptionFileName = "description/description.xml";
	private static final Logger logger = Logger.getLogger(LightDevice.class);
	
	private boolean power;
	
	public LightDevice() throws InvalidDescriptionException {
		super(descriptionFileName);
		
		power = false;
		
		setActionListener(this);
		setQueryListener(this);
	}

	public boolean isPower() {
		return power;
	}

	public void setPower(boolean power) {
		this.power = power;
	}
	
	public void powerOn() {
		power = true;
	}
	
	public void powerOff() {
		power = false;
	}
	
	public void toogleState() {
		
		if(power == true) {
			power = false;
		}
		else {
			power = true;
		}
		
	}

	@Override
	public boolean actionControlReceived(Action action) {
		
		ArgumentList argList = action.getArgumentList();
		String actionName = action.getName();
		
		if(actionName.equals("SetPower")) {
			
			logger.debug("SetPower action requested");
			
			Argument powerArg = argList.getArgument("Power");
			setPower(Boolean.parseBoolean(powerArg.getValue()));
			powerArg.setValue(String.valueOf(isPower()));
			
			return true;
		}
		else if(actionName.equals("GetPower")) {
			
			logger.debug("GetPower action requested");
			
			Argument powerArg = argList.getArgument("Power");
			powerArg.setValue(String.valueOf(isPower()));
			
			return true;
		}
		else if(actionName.equals("PowerOn")) {
			
			logger.debug("PowerOn action requested");
			
			powerOn();
			
			return true;
		}
		else if(actionName.equals("PowerOff")) {
			
			logger.debug("PowerOff action requested");
			
			powerOff();
			
			return true;
		}
		else if(actionName.equals("TogglePower")) {
			
			logger.debug("TogglePower action requested");
			
			toogleState();
			
			return true;
		}
		
		return false;
	}

	@Override
	public boolean queryControlReceived(StateVariable stateVar) {
		
		String varName = stateVar.getName();
		
		if(varName.equals("Power")) {
			
			logger.debug("Power variable requested");
			
			stateVar.setValue(String.valueOf(isPower()));
			
			return true;
		}
		
		return false;
	}
	
}
